import * as path from 'path';
import * as vscode from 'vscode';
import { SettingsManager } from '../config/settings';
import { MarkdownFile } from '../domain/markdownFile';
import { cacheManager } from './cacheManager';

export class DraftManager implements vscode.Disposable {
    private draftCache: Map<string, MarkdownFile> = new Map();
    private settingsManager: SettingsManager;

    constructor(private context: vscode.ExtensionContext) {
        this.settingsManager = new SettingsManager();
        this.watchFileChanges();
        this.initializeCache();
    }

    /**
     * 初始化缓存系统
     * 包括内存缓存和数据库缓存的初始化
     */
    private async initializeCache(): Promise<void> {
        try {
            // 初始化数据库缓存管理器
            await cacheManager.initialize(this.context);
            console.log('数据库缓存管理器初始化成功');

            if (!vscode.workspace.workspaceFolders) {
                console.log('未打开任何工作区，跳过文件扫描');
                return;
            }

            const workspaceRoot = vscode.workspace.workspaceFolders[0].uri.fsPath;
            console.log(`开始扫描工作区: ${workspaceRoot}`);

            // 扫描所有Markdown文件
            const pattern = new vscode.RelativePattern(workspaceRoot, '**/*.md');
            const files = await vscode.workspace.findFiles(pattern);
            // 排除 history_json 目录下的所有文件
            const filteredFiles = files.filter(file => !file.fsPath.includes('history_json'));
            console.log(`找到 ${filteredFiles.length} 个Markdown文件`);

            // 更新每个文件的状态
            for (const file of filteredFiles) {
                try {
                    await this.updateDraftStatus(file);
                } catch (error) {
                    console.error(`处理文件失败: ${file.fsPath}`, error);
                    // 继续处理其他文件
                    continue;
                }
            }

            console.log('缓存初始化完成');
        } catch (error) {
            console.error('缓存初始化失败:', error);
            this.handleError(error as Error);
        }
    }

    private watchFileChanges(): void {
        const watcher = vscode.workspace.createFileSystemWatcher('**/*.md');
        watcher.onDidChange((uri: vscode.Uri) => this.updateDraftStatus(uri));
        watcher.onDidCreate((uri: vscode.Uri) => this.updateDraftStatus(uri));
        watcher.onDidDelete((uri: vscode.Uri) => this.draftCache.delete(uri.fsPath));
    }

    /**
     * 更新文件的草稿状态并处理缓存
     * @param uri 文件URI
     */
    public async updateDraftStatus(uri: vscode.Uri): Promise<void> {
        try {
            const document = await vscode.workspace.openTextDocument(uri);
            const content = document.getText();
            const mdfile = MarkdownFile.from(content);

            if (!mdfile) {
                throw new Error(`无法解析Markdown文件: ${uri.fsPath}`);
            }

            // 更新内存缓存
            this.draftCache.set(uri.fsPath, mdfile);

            // 如果文件已发布（不是草稿），则添加到数据库缓存
            if (!mdfile.isDraft()) {
                await this.addToCache(uri);
                console.log(`文件已发布，添加到缓存: ${uri.fsPath}`);
            } else {
                // 如果是草稿，检查是否在缓存中，如果在则移除
                const isInCache = await this.isInCache(uri);
                if (isInCache) {
                    await this.removeFromCache(uri);
                    console.log(`文件是草稿，从缓存中移除: ${uri.fsPath}`);
                }
            }
        } catch (error) {
            this.handleError(error as Error);
        }
    }

    public isDraft(uri: vscode.Uri): boolean {
        const md_file = this.draftCache.get(uri.fsPath);
        return md_file?.isDraft() || false;
    }
    public getMdFile(uri: vscode.Uri): MarkdownFile | undefined {
        return this.draftCache.get(uri.fsPath);
    }

    public getDraftColor(): string {
        return this.settingsManager.getDraftColor();
    }

    private handleError(error: Error): void {
        console.error('Error in DraftManager:', error);
        vscode.window.showErrorMessage(`Error: ${error.message}`);
    }

    /**
     * 检查文件是否在缓存中
     * @param uri 文件URI
     * @returns Promise<boolean>
     */
    /**
     * 检查文件是否在缓存中
     * @param uri 文件URI
     * @returns Promise<boolean>
     */
    public async isInCache(uri: vscode.Uri): Promise<boolean> {
        try {
            if (!vscode.workspace.workspaceFolders) {
                return false;
            }
            const workspaceRoot = vscode.workspace.workspaceFolders[0].uri.fsPath;
            // 使用path.relative获取相对路径
            const relativePath = path.relative(workspaceRoot, uri.fsPath);
            // 规范化路径，确保使用正斜杠
            const normalizedPath = relativePath.replace(/\\/g, '/');
            return await cacheManager.isFileInCache(normalizedPath);
        } catch (error) {
            this.handleError(error as Error);
            return false;
        }
    }

    /**
     * 添加文件到缓存
     * @param uri 文件URI
     * @param remoteUrl 远程URL（可选）
     */
    public async addToCache(uri: vscode.Uri, remoteUrl?: string): Promise<void> {
        try {
            if (!vscode.workspace.workspaceFolders) {
                throw new Error('未打开任何工作区');
            }
            const workspaceRoot = vscode.workspace.workspaceFolders[0].uri.fsPath;
            const relativePath = path.relative(workspaceRoot, uri.fsPath);
            const normalizedPath = relativePath.replace(/\\/g, '/');
            await cacheManager.addToCache(normalizedPath, remoteUrl);
        } catch (error) {
            this.handleError(error as Error);
        }
    }

    /**
     * 从缓存中移除文件
     * @param uri 文件URI
     */
    public async removeFromCache(uri: vscode.Uri): Promise<void> {
        try {
            if (!vscode.workspace.workspaceFolders) {
                throw new Error('未打开任何工作区');
            }
            const workspaceRoot = vscode.workspace.workspaceFolders[0].uri.fsPath;
            const relativePath = path.relative(workspaceRoot, uri.fsPath);
            const normalizedPath = relativePath.replace(/\\/g, '/');
            await cacheManager.removeFromCache(normalizedPath);
        } catch (error) {
            this.handleError(error as Error);
        }
    }

    /**
     * 释放资源
     */
    public dispose(): void {
        cacheManager.dispose();
    }
}